﻿#region License
/*

	Copyright (C) 2008 Oliver Charles, Daniel Hollander

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/
#endregion

using System;
using System.Drawing;
using Moebius.Components;
using Moebius.Core;
using Moebius.Rendering;
using Image=Moebius.Components.Image;

namespace Overload.Entities
{
    public sealed class Terrain : Entity
    {
        private readonly World world;
        private readonly float tileSize;
        private readonly float sideLength;
        private readonly float tileHeight;
        private readonly float halfSideLength;
        private readonly float halfTileHeight;
        private readonly float gradient;

        public Terrain(World manager, float tileSize)
            : base(manager)
        {
            // TODO Would like a better way of doing this. We already store a pointer to the world manager, but
            //      we have to store it again here because we need access to the Overload specific world (World.Width, etc).
            world = manager;

            AddComponent(typeof(Image));

            this.tileSize = tileSize;

            sideLength = (tileSize / 2.0f);
            tileHeight = (float)(sideLength / Math.Tan(Math.PI / 6));
            halfSideLength = (sideLength / 2.0f);
            halfTileHeight = (tileHeight / 2.0f);
            gradient = (tileHeight / 2.0f) / halfSideLength;
        }

        public override void Initialize(ResourceFactory resourceFactory)
        {
            base.Initialize(resourceFactory);

            Image image = RequestComponent<Image>();

            // Remember to check components for null. In the test suite, we might not have an image component subsystem,
            // and this would fail
            if (image != null)
            {
                image.Initialize(world.Width * world.Height, 5);
                image.ImageAtlas = resourceFactory.Load<ImageAtlas>("Resources/Tileset.tiles");

                for (int x = 0; x < world.Width; x++)
                    for (int y = 0; y < world.Height; y++)
                    {
                        RectangleF tilePosition = CalculateTileScreenPosition(Overload.World.ArrayToHex(x, y));
                        tilePosition.Inflate(0.5f, 0.5f);

                        TileType tileType = world.GetTileFromArray(x, y).TileType;
                        image.AddQuad(tilePosition, tileType.ImageIdentifier);
                    }
            }
        }

        /// <summary>
        /// Calculate the bounds of a tile in screen space
        /// </summary>
        /// <param name="hexCoordinates">The coordinates of the tile in hexagon space</param>
        /// <returns>A RectangleF containing the bounds of the tile</returns>
        public RectangleF CalculateTileScreenPosition(Point hexCoordinates)
        {
            Point arrayCoords = Overload.World.HexToArray(hexCoordinates);

            float verticalShift = (tileHeight / 2.0f) * (arrayCoords.X % 2);
            float tileY = arrayCoords.Y * tileHeight + verticalShift;

            float horizontalOffset = (float)(Math.Ceiling(sideLength + halfSideLength));
            float tileX = arrayCoords.X * horizontalOffset;

            return new RectangleF(tileX, tileY, tileSize, tileHeight);
        }

        public Point CalculateTileCoordinatesFromScreenSpace(Point space)
        {
            int sectX = (int)Math.Floor(space.X / (sideLength + halfSideLength));
            int sectY = (int)Math.Floor(space.Y / tileHeight);

            int sectPixelX = (int)(space.X - sectX * (halfSideLength + sideLength));
            int sectPixelY = (int)(space.Y - sectY * tileHeight);

            int arrayX = sectX;
            int arrayY = sectY;

            if (sectX % 2 == 0)
            {
                if (sectPixelX < halfSideLength)
                    if (sectPixelY < (halfTileHeight - gradient*sectPixelX))
                    {
                        arrayX--;
                        arrayY--;
                    }
                    else if (sectPixelY > (halfTileHeight + gradient*sectPixelY))
                        arrayX--;
            }
            else
            {
                if (sectPixelX < halfSideLength)
                {
                    if (sectPixelY < (gradient * sectPixelX))
                        arrayY--;
                    else if (sectPixelY <= (tileHeight - gradient * sectPixelY))
                        arrayX--;
                }
                else
                    if (sectPixelY < halfTileHeight)
                        arrayY--;
            }

            return Overload.World.ArrayToHex(arrayX, arrayY);
        }
    }
}